package org.swan.web.user.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.user.bean.UserBean;
import org.swan.web.user.mapper.UserMapper;
import org.swan.web.user.service.UserService;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Override
    public Optional<UserBean> getUserById(long id) {
        if(id == -1L)
        return Optional.of(UserBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(UserMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addUser(UserBean userBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(UserMapper.class).add(userBean), Long.class);
        return result;
    }

    @Override
    public UserBean updateUser(UserBean userBean) {
        getUserById(userBean.getUserId()).orElseThrow(()->new BusinessException(BusinessCode.USER_DO_NOT_EXIST,userBean.getUserId()));
        ADOConnection.runTask(factory -> factory.getMapper(UserMapper.class).updateById(userBean), Long.class);
        return getUserById(userBean.getUserId()).get();
    }

    @Override
    public UserBean deleteUserById(long userId) {
        UserBean userBean = getUserById(userId).orElseThrow(()->new BusinessException(BusinessCode.USER_DO_NOT_EXIST,userId));
        ADOConnection.runTask(factory -> factory.getMapper(UserMapper.class).deleteById(userId), Long.class);
        return userBean;
    }

    @Override
    public List<UserBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(UserMapper.class).list(offset, rows), List.class);
    }


}
